package com.zlt.dao.Impl;

import com.zlt.dao.InterviewDao;
import com.zlt.entity.Interview;
import com.zlt.entity.ViewInterview;
import com.zlt.util.JDBCUtil;
import com.zlt.util.SqlUtil;
import com.zlt.vo.InterviewVo;
import com.zlt.vo.Pager;
import org.springframework.jdbc.core.BeanPropertyRowMapper;

import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;

public class InterviewDaoImpl implements InterviewDao {

    JdbcTemplate template = new JdbcTemplate(JDBCUtil.getDataSource());

    @Override
    public int insertInterview(Interview interview) {
        return SqlUtil.insert(interview);
    }

    @Override
    public Long selectInterviewCount() {
        String sql = "select count(*) from interview";
        return (Long) SqlUtil.select(sql).get(0).get("c");
    }

    @Override
    public List<Interview> selectAllInterview(String initiator, Integer cid, Pager<InterviewVo> pager) {
        String sql = "select id,name,initiator_id,uid,cid,send_time,valid_time,state,note,address,interview_time from interview where initiator_id=? and cid=? limit ?,?";
        return SqlUtil. select(Interview.class,sql,initiator,cid,(pager.getPage() - 1) * pager.getLimit(),pager.getLimit());
    }

    @Override
    public int updateInterview(Integer id, String state) {
        String sql = "update interview set state=? where id=?";
        return SqlUtil.update(sql,state,id);
    }

    @Override
    public List<ViewInterview> getInterviewViewByUsername(String username) {
        String sql = "SELECT i.id,c.cname AS companyName,i.send_time AS sendTime,i.valid_time AS validTime,i.state,i.note,i.name,u.nickname AS initiator,i.interview_time AS interviewTime,i.address FROM interview AS i, company AS c,user AS u WHERE c.cid = i.cid AND i.initiator_id = u.uid AND i.uid = (SELECT uid FROM user WHERE username = ? )";
        return template.query(sql, BeanPropertyRowMapper.newInstance(ViewInterview.class),username);
    }

    @Override
    public boolean setInterviewState(String username,String id, String state) {
        String sql = "UPDATE interview SET state = ? WHERE uid = (SELECT uid FROM user WHERE username = ?) AND id = ?";
        return template.update(sql,state,username,id)>0?true:false;
    }
}
